package com.ubxtech.nacos.util;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.ConfigType;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.shaded.com.google.common.io.CharStreams;
import com.alibaba.nacos.shaded.com.google.common.io.LineReader;

import java.io.BufferedReader;
import java.io.File;
import java.io.Reader;
import java.io.StringReader;
import java.util.*;

/**
 * @author Victor.Xiao
 * @since 2024-01-22 14:29
 **/
public class I18nLoadExcelUtil {

    public static final String FLAG_STR = "#===excel keys===========";

    /**
     *
     * @author Victor.Xiao
     * @since 2024-01-22 17:00
     * @param excelFile excelFile
     * @param sheetName sheetName
     * @param i18nDir i18nDir
     * @param append 是否要添加excel中没映射的key
    */
    public static void replaceFile(String excelFile, String sheetName, String i18nDir,boolean append) {
        //文件名,value是excel中对应的第几列
        Map<String, Integer> i18nRs = new HashMap<>();
        i18nRs.put("简体中文.properties",1);
        i18nRs.put("英语.properties",2);
        i18nRs.put("韩语.properties",3);
        i18nRs.put("德语.properties",4);
        i18nRs.put("日语.properties",5);
        i18nRs.put("法语.properties",6);
        i18nRs.put("荷兰语.properties",7);
        i18nRs.put("波兰语.properties",8);
        i18nRs.put("匈牙利语.properties",9);
        i18nRs.put("西班牙语.properties",10);
        i18nRs.put("意大利.properties",11);
        i18nRs.put("葡萄牙语.properties",12);
        i18nRs.put("土耳其.properties",13);
        i18nRs.put("俄语.properties",14);
        i18nRs.put("泰语.properties",15);

        Map<String, List<Object>> keyMap = getExcelData(excelFile, sheetName);

        FileUtil.copyFilesFromDir(new File(i18nDir), new File(i18nDir + "_bak_"+System.currentTimeMillis()), true);

        File[] propertiesList = new File(i18nDir).listFiles();
        if (propertiesList == null) {
            return;
        }
        for (File file : propertiesList) {
            String curFileName = file.getName();
            System.out.println("替换"+curFileName);
            Integer col = i18nRs.get(curFileName);
            if (col == null) {
                System.out.println("没有配置翻译文件对应哪一列");
                continue;
            }

            List<String> lineList = FileUtil.readUtf8Lines(file);
            //替换后的
            List<String> lineListReplace = lineReplace(lineList, keyMap, col, curFileName, append);

            FileUtil.writeUtf8Lines(lineListReplace, file);
        }
    }

    /**
     *
     * @author Victor.Xiao
     * @since 2024-03-01 11:33
     * @param excelFile excelFile
     * @param sheetName sheetName
     * @return key是第一行列值,list是所有列的值
    */
    public static Map<String, List<Object>> getExcelData(String excelFile, String sheetName) {
        ExcelReader excelReader = ExcelUtil.getReader(new File(excelFile), sheetName);
        List<List<Object>> translateTextList = excelReader.read(1);
        Map<String, List<Object>> keyMap = new HashMap<>();

        for (List<Object> line : translateTextList) {
            String key = line.get(0).toString();
            if (StrUtil.isBlank(key)) {
                continue;
            }

            keyMap.put(StrUtil.trim(key), line);
        }
        return keyMap;
    }

    /**
     *
     * @author Victor.Xiao
     * @since 2024-03-01 11:34
     * @param lineList 已有的数据
     * @param keyMap excel数据
     * @param col col
     * @param curDataId curDataId
     * @param append append
     * @return java.util.List<java.lang.String>
    */
    private static List<String> lineReplace(List<String> lineList,Map<String, List<Object>> keyMap,int col,String curDataId,boolean append) {
        //替换后的
        List<String> lineListReplace = new ArrayList<>();
        //能匹配上的key
        Set<String> replacedKeys = new HashSet<>();

        for (String oldLine : lineList) {
            //标志行,则过滤
            if (FLAG_STR.equals(oldLine)) {
                continue;
            }
            //空或者注释行保留
            if (StrUtil.isBlank(oldLine) || oldLine.startsWith("#")) {
                lineListReplace.add(oldLine);
                continue;
            }
            //没有等号,非法的行去掉
            if (!oldLine.contains("=")) {
                System.out.println(curDataId + ", oldData :" + oldLine + ",col:" + col + ",原来的值非法,过滤掉");
                continue;
            }
            String[] splitStr = oldLine.split("=");
            String key = splitStr[0];
//            //key为空不写入
            if (StrUtil.isBlank(splitStr[0])) {
                System.out.println(curDataId + ", oldData :" + oldLine + ",col:" + col + ",原来的值为空,过滤掉");
                continue;
            }
            List<Object> lineTranslate = keyMap.get(key);
            if (CollectionUtil.isEmpty(lineTranslate)) {
                lineListReplace.add(oldLine);
                continue;
            }
            if (lineTranslate.get(col) == null) {
                System.out.println(curDataId+", oldData :"+oldLine+",col:"+col+",excel中翻译文本为空");
                continue;
            }
            String replaceValue = lineTranslate.get(col).toString();
            if (StrUtil.isBlank(replaceValue)) {
                System.out.println(curDataId+", oldData :"+oldLine+",col:"+col+",excel中翻译文本为空");
                continue;
            }
            replacedKeys.add(key);
            //替换换行符  text.replace("\n", "").replace("\r\n", "").replace("\r", "");
            replaceValue = replaceValue.replaceAll("\r\n", " ").replaceAll("\n", " ").replaceAll("\r", " ");
            lineListReplace.add(key + "=" + replaceValue);
        }
        //要不要把excel中未匹配到的key添加到文件中
        if (append) {
            Map<String, List<Object>> keyMapClone = new HashMap<>(keyMap);
            if (replacedKeys.size() > 0) {
                for (String replacedKey : replacedKeys) {
                    keyMapClone.remove(replacedKey);
                }
            }
            if (keyMapClone.size() > 0) {

                lineListReplace.add("");
                lineListReplace.add(FLAG_STR);
                keyMapClone.forEach((key,value) ->{
                    if (value.get(col)!=null && StrUtil.isNotBlank(value.get(col).toString())) {
                        lineListReplace.add(key + "=" + value.get(col).toString());
                    }
                });
            }
        }
        return lineListReplace;
    }

    /**
     *
     * @author Victor.Xiao
     * @since 2024-01-22 17:00
     * @param excelFile excelFile
     * @param sheetName sheetName
     * @param append 是否要添加excel中没映射的key
     */
    public static void replaceNacos(String excelFile, String sheetName, boolean append
            ,String serverAddr
            ,String group
            ,String namespace
            ,String username
            ,String password
    ) {
        try {
            Map<String, Integer> i18nRs = new HashMap<>();
            i18nRs.put("i18n-zh_CN.properties",1);
            i18nRs.put("i18n-en_US.properties",2);
            i18nRs.put("i18n-ko_KR.properties",3);
            i18nRs.put("i18n-de_DE.properties",4);
            i18nRs.put("i18n-ja_JP.properties",5);
            i18nRs.put("i18n-fr_FR.properties",6);
            i18nRs.put("i18n-nl_NL.properties",7);
            i18nRs.put("i18n-pl_PL.properties",8);
            i18nRs.put("i18n-hu_HU.properties",9);
            i18nRs.put("i18n-es_ES.properties",10);
            i18nRs.put("i18n-it_IT.properties",11);
            i18nRs.put("i18n-pt_PT.properties",12);
            i18nRs.put("i18n-tr_TR.properties",13);
            i18nRs.put("i18n-ru_RU.properties",14);
            i18nRs.put("i18n-th_TH.properties",15);

            Properties properties = new Properties();
            properties.put("serverAddr", serverAddr);
            properties.put("namespace", namespace);
            properties.put("username", username);
            properties.put("password", password);
            ConfigService configService = NacosFactory.createConfigService(properties);
            //key是第一行列值,list是所有列的值
            Map<String, List<Object>> keyMap = getExcelData(excelFile, sheetName);
            for (Map.Entry<String, Integer> entry : i18nRs.entrySet()) {
                String dataId = entry.getKey();
                Integer col = entry.getValue();
                String content = configService.getConfig(dataId, group, 5000);
                if (StrUtil.isBlank(content)) {
                    System.out.println("读取配置文件为空:" + dataId);
                    continue;
                }
                //nacos中的内容
                List<String> lineList = CharStreams.readLines(new StringReader(content));
                //替换后的
                List<String> lineListReplace = lineReplace(lineList, keyMap, col, dataId, append);

                StringBuffer sb = new StringBuffer();
                for (String s : lineListReplace) {
                    sb.append(s).append("\n");
                }
                configService.publishConfig(dataId, group, sb.toString(), ConfigType.PROPERTIES.getType());

            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        String excelFile = "C:\\Users\\victor.xiao\\Desktop\\fsdownload\\送餐机器人字段.xlsx";
        String sheetName = "crms";
        String i18nDir = "E:\\商用机器\\i18n";
//        I18nLoadExcelUtil.replaceFile(excelFile,sheetName,i18nDir,true);

        I18nLoadExcelUtil.replaceNacos(excelFile,sheetName,true
                ,"10.10.17.66:8848"
                ,"cml-cloud"
                ,"3bd2ced7-9fdb-4ff6-ba63-7a3b3284eef4"
                ,"nacos"
                ,"nacos_cml_dev"
        );
    }
}
